const path = require("path");
const { sep } = path;
const glob = require("glob");
// 匹配当前目录及其子目录下的所有.js文件，并将匹配到的文件路径打印出来‌

/**
 * service loader
 * @param {object} app Koa  实例
 * 加载所有service 可以通过 'app.service.${目录}.${文件}' 访问
 * 
  例子 app/service
   |
   | -- custom-module
            |
            | -- custom-service.js
   => app.service.customModule.customService
  */
module.exports = (app) => {
  // 读取 app/service/**/**.js
  const servicePath = path.resolve(app.businessPath, `.${sep}service`);

  const fileList = glob.sync(path.resolve(servicePath, `.${sep}**${sep}**.js`));
  const service = {};
  // 遍历所有的文件目录 把内容加载到app.controller下
  fileList.forEach((file) => {
    // 获取文件名称
    let name = path.resolve(file);
    name = name.substring(
      name.lastIndexOf(`service${sep}`) + `service${sep}`.length,
      name.lastIndexOf(".")
    ); // 把 '-'统一改为驼峰 custom-module/custom-middleware =>customModule.customMiddleware
    name = name.replace(/[_-][a-z]/gi, (s) => s.substring(1).toUpperCase());
    let tempService = service;

    const names = name.split(sep);
    for (let i = 0, len = names.length; i < len; ++i) {
      if (i === len - 1) {
        const ServiceModule = require(path.resolve(file))(app);
        tempService[names[i]] = new ServiceModule();
      } else {
        if (!tempService[names[i]]) {
          tempService[names[i]] = {};
        }
        tempService = tempService[names[i]];
      }
    }
  });
  app.service = service;
};
